<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
      <div>
        选择商品分类:
        <el-cascader
          expand-trigger="hover"
          :options="getCateinfos"
          :props="props"
          v-model="selectedCateKeys"
          @change="handleChange"
        ></el-cascader>
      </div>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDiagdialogVisible=true"
          >添加参数</el-button>
          <!-- 动态参数的表格 -->
          <el-table :data="manyTableDate" border stripe>
            <el-table-column type="expand">
              <!-- 展开行 -->
              <template slot-scope="scope">
                <el-tag v-for="(item , index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>

                <!-- 循环处理展开行的tag标签     -->
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDiagdialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性的表格 -->
          <el-table :data="onlyTableDate" border stripe>
            <el-table-column type="expand">
              
              <!-- 展开行 -->
              <template slot-scope="scope">
                <el-tag v-for="(item , index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>

                <!-- 循环处理展开行的tag标签     -->
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>

            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加参数的对话框 -->
      <el-dialog
        :title="'添加'+titleText"
        :visible.sync="addDiagdialogVisible"
        width="50%"
        @close="addDiagClosed"
      >
        <!-- 添加参数的对话框 -->
        <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDiagdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改参数对话框 -->

      <el-dialog
        :title="'修改'+titleText"
        :visible.sync="editDiagdialogVisible"
        width="50%"
        @close="editDiagClosed"
      >
        <!-- 添加参数的对话框 -->
        <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDiagdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
export default {
  data() {
    return {
      getCateinfos: [],
      // 级连选择框双向绑定的数组
      selectedCateKeys: [],
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyTableDate: [],
      onlyTableDate: [],
      addDiagdialogVisible: false,
      addForm: {
        attr_name: ''
      },
      // 添加表单的验证规则
      addFormrules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      editDiagdialogVisible: false,
      editForm: {
        attr_name: ''
      },
      // 添加表单的验证规则
      editFormrules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
   
    async getCateinfo() {
      let { data: res } = await this.axios.get('categories')
      console.log(res)
      if (res.meta.status != 200) return this.$message.error('请求出错')
      this.getCateinfos = res.data
    },
    handleChange() {
      this.getParmsData()
    },
    async getParmsData() {
      // 如果选中的不是三级菜单则清空
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []

        return
      }

      // 通过书宣的分类和当前的面板获取对应的餐宿
      //   id=this.selectedCateKeys[2];

      let { data: res } = await this.axios.get(`categories/${this.cateID}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status != 200) return this.$message.error('获取信息失败')
      // 判断获取的数据是动态属性还是静态属性
      // 对数据进行处理使用空格做分割
      // 处理前需要对数据进行对比如果是空则直接返回 不然存在bug
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible=false
        item.inputValue=''
      })
      console.log(res.data)

      if (this.activeName == 'many') {
        this.manyTableDate = res.data
      } else {
        this.onlyTableDate = res.data
      }
    },

    handleClick(tab, event) {
      console.log(tab, event)
      this.getParmsData()
    },
    addDiagClosed() {
      this.$refs.addFormRef.resetFields()
      this.addDiagdialogVisible = false
    },
    async showEditDialog(attr_id) {
      let { data: res } = await this.axios.get(`categories/${this.cateID}/attributes/${attr_id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status != 200) return this.$message.error('获取信息错误')
      this.editForm = res.data
      this.editDiagdialogVisible = true
    },

    editDiagClosed() {
      this.$refs.editFormRef.resetFields()
      this.editDiagdialogVisible = false
    },
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.axios.post(`categories/${this.cateID}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status != 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDiagdialogVisible = false
      })
    },
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.axios.put(`categories/${this.cateID}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status != 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.getParmsData()
        this.editDiagdialogVisible = false
      })
    },
    async removeParams(attr_id) {
      let res = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res !== 'confirm') return this.$message.error('已经取消')
      let { data: rest } = await this.axios.delete(`categories/${this.cateID}/attributes/${attr_id}`)
      if (rest.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParmsData()
    },
     // 文本框失去焦点或者按下回车都会触发
    async handleInputConfirm(rows){
      // console.log('ok');
      if(rows.inputValue.trim().length==0){
         rows.inputValue='',
      rows.inputVisible=false
      return
      }
     
      // 如果没有return 则表示用户输入了正确的数据
      rows.attr_vals.push(rows.inputValue.trim());
      rows.inputValue=''
      rows.inputVisible=false
      // 发起请求保存数据
     let {data:res}=await this.axios.put(`categories/${this.cateID}/attributes/${rows.attr_id}`,{
        attr_name:rows.attr_name,
        attr_sel:rows.attr_sel,
        attr_vals:rows.attr_vals.join(' ')
      })
      console.log(res);
      
      if(res.meta.status!=200) return this.$message.error('提交出错')
      this.$message.success('提交成功')
      
    },
    showInput(rows){
      // console.log(rows);
       rows.inputVisible=true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 删除对应的参数可选项
    handleClose(id,row){
    row.attr_vals.splice(id,1);
    
    // 然后保存到后台
    this.saveAttrVals(row)
    },
    async saveAttrVals(rows){
      // 发起请求保存数据
     let {data:res}=await this.axios.put(`categories/${this.cateID}/attributes/${rows.attr_id}`,{
        attr_name:rows.attr_name,
        attr_sel:rows.attr_sel,
        attr_vals:rows.attr_vals.join(' ')
      })
      console.log(res);
      
      if(res.meta.status!=200) return this.$message.error('提交出错')
      this.$message.success('提交成功')
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 动态计算选中数组的长度
    cateID() {
      if (this.selectedCateKeys.length == 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 动态计算标题的文本是动态参数还是静态属性
    titleText() {
      if (this.activeName == 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created() {
    this.getCateinfo()
  }
}
</script>


<style lang="less" scoped>
.el-alert {
  margin: 15px 0;
  font-size: 20px;
}
.el-tag {
  margin: 0 15px;
};
.button-new-tag {
  width:120px;
}
</style>
